package com.auto.survey.activity.config

import android.graphics.Color
import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.widget.ViewPager2
import com.auto.survey.R
import com.auto.survey.activity.config.dao.ConfigDao
import com.auto.survey.activity.config.dao.ConfigDbCallback
import com.auto.survey.activity.config.dao.ConfigRepository
import com.auto.survey.activity.config.entity.ConfigBean
import com.auto.survey.activity.config.entity.ConfigWithPoints
import com.auto.survey.activity.config.entity.PointConfig
import com.auto.survey.base.BaseActivity
import com.auto.survey.base.CustomApplication
import com.auto.survey.base.ICreatView
import com.auto.survey.database.AppDatabase
import com.auto.survey.log.AppLogger
import com.auto.survey.util.Helper
import com.auto.survey.widget.CentreToast
import com.auto.survey.widget.CommonTitle.Companion.TEXT_POSITON_RIGHT
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.gson.Gson
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 基础配置页面
 */
class ConfigActivity :BaseActivity() {
    companion object {
        private val TAG:String = ConfigActivity::class.java.simpleName
    }

    private lateinit var repository:ConfigRepository
    private var pointConfigs:MutableList<PointConfig> = mutableListOf()
    private var configrlt: ConfigBean = ConfigBean(pc_data=0.0, tmp_data=0.0, hum_data=0.0, kap_data=0.0, higt_data=0.0,stnum_data=0)
    private var bean: ConfigWithPoints = ConfigWithPoints(configrlt, pointConfigs)
    private val viewModel: ConfigViewModle by viewModels()

    private lateinit var viewPager: ViewPager2
    private lateinit var tabLayout: TabLayout


    override fun initView() {
        //initdata
        val db:AppDatabase = AppDatabase.getInstance(CustomApplication.getContext())
        val configDao: ConfigDao = db.configDao()
        repository = ConfigRepository(configDao)
        //viewModel监听各个页面的变化
        viewModel.getConfigDataByDao(repository)
//        lifecycleScope.launch {
//            repository.deleteAll()
//        }

        val viewCreators: List<ICreatView> = listOf(
            ConfigSurveyStationView(configrlt, viewModel,this@ConfigActivity),
            ConfigSurveyPointView(pointConfigs, viewModel, this@ConfigActivity),
            ConfigToleranceView()
        )

        //ui
        mTopBar?.visibility = View.VISIBLE
        mTopBar?.setBackgroundResource(R.color.action_bar)

        mComment_title?.visibility = View.VISIBLE
        mComment_title?.setBackgroundResource(R.color.action_bar)
        mComment_title?.setTitle("测站测点限差配置")

        mComment_title?.setRightTitle("保存")
        mComment_title?.setTitleColor(Color.WHITE, TEXT_POSITON_RIGHT)
        mComment_title?.setOnRightTextClickListener(Helper.debounce{
            onSaveTextClick(viewCreators)
        })

        viewPager = findViewById(R.id.viewPager)
        tabLayout = findViewById(R.id.tabLayout)



        val views = mutableListOf<View>()
        try {
            viewCreators.forEach { creator ->
                creator.creatView(viewPager.context, viewPager)
                views.add(creator.getView())
            }
        } catch (e: Exception) {
            AppLogger.getInstance(this@ConfigActivity).e(TAG, "创建视图失败: ${e.message}", e)
            // 可添加默认视图或空状态处理
        }

        val adapter = ViewPagerAdapter()
        adapter.setViews(views)
        // 设置适配器
        viewPager.adapter = adapter

        // 配置 TabLayout
        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            if (position < viewCreators.size) {
                tab.text = viewCreators[position].getTitle()
            } else {
                tab.text = "未知页面" // 处理越界情况
            }
        }.attach()


        lifecycleScope.launch {

            viewModel.bean.observe(this@ConfigActivity) { it->
                if (it != null) {
                    bean = it
                }

            }

            viewModel.points.observe(this@ConfigActivity){ it->
                if (it != null) {
                    bean.points = it
                }
            }

            viewModel.station.observe(this@ConfigActivity){ it->
                if (it != null) {
                    bean.config = it
                }
            }
        }
    }

    private fun onSaveTextClick(viewCreators: List<ICreatView>) {
        var temp = true
        viewCreators.dropWhile {
            it.checkView()
        }.forEach { creator ->
            temp = false
        }

        if (temp) {

            CoroutineScope(Dispatchers.IO).launch {
//                repository.deleteAll()
                val json = Gson().toJson(bean)
                Log.d(TAG,"json: $json")
                repository.setConfigsWithPoints(object : ConfigDbCallback{
                    override fun call(result: Int, msg:String) {
                        Log.d(TAG,"result: $result, ===> $msg")
                        lifecycleScope.launch {
                            withContext(Dispatchers.Main) {
                                if (result == -1000) {
                                    CentreToast.instance.show("数据库操作失败", false)
                                    AppLogger.getInstance(this@ConfigActivity).i(TAG, "添加配置数据库操作失败: $msg")
                                } else {
                                    CentreToast.instance.show("保存成功", true)
                                }
                            }
                        }
                    }
                }, bean)
            }

        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_config
    }
}